//
//  NetWorking.m
//  JiangDuStateTax
//
//  Created by MAXMFJ on 15/11/11.
//  Copyright © 2015年 MAX-MENGFANJIE. All rights reserved.
//

#import "NetWorking.h"
#import <AFNetworking.h>
@implementation NetWorking

+(void)addNetWorking:(NSMutableDictionary *)dataDictionary url:(NSString *)url block:(DATADICT)block
{
   
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [session.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [session POST:url parameters:dataDictionary progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%@",dataDictionary);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * responseString = [[NSString alloc] initWithData:responseObject   encoding:NSUTF8StringEncoding];
        NSMutableDictionary*dict= [NSJSONSerialization JSONObjectWithData:[self dataWithJson:responseString]  options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"*url:%@  *%@",url,[self dictionaryToJson:dict]);

        block(dict, [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]], [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]]);
        

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@------%@-----%@", [error localizedDescription],url,dataDictionary);
        block(nil,@"error",[NSString stringWithFormat:@"%ld",error.code]);
    }];
    
    
 
}
+(void)addNetWorkings:(NSMutableDictionary *)dataDictionary url:(NSString *)url block:(DATADICT)block
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [session.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [session POST:url parameters:dataDictionary progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%@",dataDictionary);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * responseString = [[NSString alloc] initWithData:responseObject   encoding:NSUTF8StringEncoding];
        NSMutableDictionary*dict= [NSJSONSerialization JSONObjectWithData:[self dataWithJson:responseString]  options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"**%@",[self dictionaryToJson:dict]);
       
        NSString * str = [[dict objectForKey:@"data"] objectForKey:@"msg"];
        if (str.length < 1||str == nil)
        {
            str = @"success";
        }
        
        block(dict, [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]],str);
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@------%@-----%@", [error localizedDescription],url,dataDictionary);
        block(nil,@"error",[NSString stringWithFormat:@"%ld",error.code]);
    }];
    
}
+(void)addNetWorkingAddImage:(NSMutableDictionary *)dataDictionary imageFile:(NSArray *)imageDatas url:(NSString *)url block:(DATADICT)block
{
    if (imageDatas.count < 1 ||imageDatas == nil)
    {
        [self addNetWorking:dataDictionary url:url block:^(NSMutableDictionary *dictionary, NSString *error, NSString *networkingError) {
            block(dictionary,error,networkingError);
        }];
        return;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
  //  [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager POST:url parameters:dataDictionary constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSInteger imgCount = 0;
        
        for (NSData *imageData in imageDatas) {
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss:SSS";
            
            NSString *fileName = [NSString stringWithFormat:@"%@%@.png",[formatter stringFromDate:[NSDate date]],@(imgCount)];
            
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
            
            
            //     [formData appendPartWithFileData :imageData name:@"fileUrl" fileName:@"userImage.png" mimeType:@"image/jpg/png"];
            imgCount++;
            
        }
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * responseString = [[NSString alloc] initWithData:responseObject   encoding:NSUTF8StringEncoding];
        NSMutableDictionary*dict= [NSJSONSerialization JSONObjectWithData:[self dataWithJson:responseString]  options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"**%@",[self dictionaryToJson:dict]);
        
           block(dict, [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]], [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        block(nil,@"error",[NSString stringWithFormat:@"%ld",error.code]);
    }];

//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.requestSerializer = [AFHTTPRequestSerializer serializer];
//    session.responseSerializer = [AFHTTPResponseSerializer serializer];
//    
//    for (NSData *imageData in imageDatas) {
//        
//                   // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        
//                   // formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss:SSS";
//        
//                    //NSString *fileName = [NSString stringWithFormat:@"%@%@.png",[formatter stringFromDate:[NSDate date]],@(imgCount)];
//        
//                  //  [formData appendPartWithFileData:imageData name:@"upload" fileName:fileName mimeType:@"image/png"];
//        
//        
//        
//                    
//                   // imgCount++;
//                    
//                }
//    NSData * data = imageDatas[0];
//
//    //NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
//    NSDictionary *dict =[self Base64PasswdWithDict:dataDictionary];
//    [dict setValue:data forKey:@"upload"];
//    [session POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSString * responseString = [[NSString alloc] initWithData:responseObject   encoding:NSUTF8StringEncoding];
//        NSMutableDictionary*dict= [NSJSONSerialization JSONObjectWithData:responseObject  options:NSJSONReadingAllowFragments error:nil];
//        
//        NSLog(@"**%@",[self dictionaryToJson:dict]);
//        block(dict, [NSString stringWithFormat:@"%@",[dict objectForKey:@"success"]], [NSString stringWithFormat:@"%@",[dict objectForKey:@"msg"]]);
//        
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@",error);
//        block(nil,@"error",@"error");
//    }];
    
}
+(void)addNetWorkingAddImages:(NSMutableDictionary *)dataDictionary imageFile:(NSArray *)imageDatas url:(NSString *)url block:(DATADICT)block
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:dataDictionary constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSInteger imgCount = 0;
        
        for (NSData *imageData in imageDatas) {
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss:SSS";
            
            NSString *fileName = [NSString stringWithFormat:@"%@%@.png",[formatter stringFromDate:[NSDate date]],@(imgCount)];
            
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
            
            
       //     [formData appendPartWithFileData :imageData name:@"fileUrl" fileName:@"userImage.png" mimeType:@"image/jpg/png"];

            
            imgCount++;
            
        }

        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSString * responseString = [[NSString alloc] initWithData:responseObject   encoding:NSUTF8StringEncoding];
        NSLog(@"%@",responseString);

        NSMutableDictionary*dict= [NSJSONSerialization JSONObjectWithData:[self dataWithJson:responseString]  options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"**%@",[self dictionaryToJson:dict]);
        
          block(dict, [NSString stringWithFormat:@"%@",[dict objectForKey:@"success"]], [NSString stringWithFormat:@"%@",[dict objectForKey:@"msg"]]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        block(nil,@"error",@"error");
    }];

    


}

+(void)addNetWorkingGet:(NSMutableDictionary *)dataDictionary url:(NSString *)url block:(DATADICT)block
{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [session GET:url parameters:dataDictionary progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       // NSString * responseString = [[NSString alloc] initWithData:responseObject   encoding:NSUTF8StringEncoding];
        NSMutableDictionary*dict= [NSJSONSerialization JSONObjectWithData:responseObject  options:NSJSONReadingAllowFragments error:nil];
        
     
        
//        NSLog(@"**%@",[self dictionaryToJson:dict]);
        block(dict, @"success", @"error");
        
        NSArray * array = [url componentsSeparatedByString:@"pg"];
        if ([array[1] isEqualToString:@"100"])
        {
            NSLog(@"第100个请求已经出现");
            [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"100s"];
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        block(nil,@"error",@"error");
    }];
    
    
    
}

+(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    if (dic.count <  1)
    {
        return @"";
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

//+(NSMutableDictionary *)Base64PasswdWithDict:(NSMutableDictionary *)parameters
//{
//     CRSA *cc = [CRSA shareInstance];
//    NSMutableDictionary *  dict = [NSMutableDictionary dictionary];
//    NSString * str = [self dictionaryToJson:parameters];
//    NSString * dataStr = [cc encryptByRsaWithCutData:[str base64EncodedString] keyType:(KeyTypePublic)];
//    [dict setObject:dataStr forKey:@"s"];
//    [dict setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"versionCode"];
//    [dict setObject:@"iOS" forKey:@"deviceType"];
//
//    return dict;
//}
//+(NSMutableDictionary *)Base64ImagePasswdWithDict:(NSMutableDictionary *)parameters
//                                            image:(UIImage *)image;
//{
//    NSMutableDictionary *  dict = [NSMutableDictionary dictionary];
//    NSString * str = [self dictionaryToJson:parameters];
//    [dict setObject:dataStr forKey:@"s"];
//    [dict setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"versionCode"];
//    [dict setObject:@"iOS" forKey:@"deviceType"];
//    [dict setObject:[parameters objectForKey:@"userId"] forKey:@"userId"];
//
//    return dict;
//}


+(NSData *)dataWithJson:(NSString *)str
{
    NSData* xmlData = [str dataUsingEncoding:NSUTF8StringEncoding];
    return xmlData;
}
@end
